package com.bakend.modules.chat;

import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.SocketChannelConfig;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;

import java.nio.ByteOrder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class ChatChannelInitializer extends ChannelInitializer<SocketChannel> {
    /**
     * 是否设置超时秒值，如果为0则不设置
     */
    private final int iTimeout;
    private final ByteBufAllocator allocator = new PooledByteBufAllocator(true);



    public ChatChannelInitializer(int iTimeout) {
        this.iTimeout = iTimeout;

    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //设置缓存的分配器--每一个socket都对应一个Allocator
        //一个Allocator有多个threadCache,但是一个thread只能与一个threadCache进行绑定，绑定成功后，就不能再次改变了
        //是否会出现一个Allocator下的treadCache个数不能被所有的thread 平均分配
        //ThreadCache --用来针对某个线程下的内存分配，如果所有的线程对象共用一个
        SocketChannelConfig config = ch.config();
        config.setAllocator(allocator);
        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 200 * 1024, 0, 4, -4, 0, true));

        //加入超时
        if (iTimeout > 0) {
            ch.pipeline().addLast("readTimeOut", new ReadTimeoutHandler(iTimeout));
        }

        ch.pipeline().addLast(new NettyMsgAdapter());//消息处理函数
    }


}
